﻿//-----------------------------------------------------------------------
// <copyright file="MainPage.cs" company="Microsoft Corporation">
//     Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
// </copyright>
//-----------------------------------------------------------------------
namespace vsarFlightPlanSupport
{
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Xml.Linq;
    using VisualStudioOnlineOData;
    using Windows.ApplicationModel.Background;
    using Windows.Storage;

    /// <summary>
    ///
    /// </summary>
    public sealed class BackgroundTask : IBackgroundTask
    {
        /// <summary>
        /// Runs the specified task instance.
        /// </summary>
        /// <param name="taskInstance">The task instance.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();
            var settings = ApplicationData.Current.RoamingSettings.CreateContainer("settings", ApplicationDataCreateDisposition.Always);
            var queryId = Read<string>(settings, "queryId", null);
            var account = Read<string>(settings, "account", null);
            var username = Read<string>(settings, "username", null);
            var password = Read<string>(settings, "password", null);
            var credentials = default(Credentials);
            if (!string.IsNullOrWhiteSpace(queryId) &&
                !string.IsNullOrWhiteSpace(account) &&
                !string.IsNullOrWhiteSpace(username) &&
                !string.IsNullOrWhiteSpace(password))
            {
                credentials = new Credentials(account, username, password);
            }

            if (credentials != null)
            {
                await WorkItems.GetWorkItemsAsync(credentials, queryId, async s => { await SaveWorkItems(s); });
            }

            deferral.Complete();
        }

        private static T Read<T>(ApplicationDataContainer container, string key, T @default)
        {
            if (container.Values.ContainsKey(key))
            {
                return (T)container.Values[key];
            }

            return @default;
        }

        private async Task SaveWorkItems(XDocument workItems)
        {
            workItems.Root.Add(new XAttribute("date", DateTime.Now));
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("workItems", CreationCollisionOption.ReplaceExisting);
            using (var stream = await file.OpenStreamForWriteAsync())
            {
                workItems.Save(stream);
            }
        }
    }
}